package javase.javase02.networkprograming;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: Gan
 * @date 2021/4/23 0023 20:11
 * @description:服务器端 2.客户端上传图片到服务器
 **/
public class ServerWork2 {
    public static void main(String[] args) throws IOException {
        //1.创建服务器端的ServerSocket对象
        ServerSocket serverSocket = new ServerSocket(3345);
        //2.获取Socket对象
        Socket socket = serverSocket.accept();
        //获取客户端IP
        String ip = socket.getInetAddress().getHostAddress();
        System.out.println(ip + "发送来了一张图片：");
        // 从socket中根据需要获取输入流
        InputStream in = socket.getInputStream();
        //将图片存到d盘中
        File dir = new File("d:\\temp");
        File file = new File(dir, ip + ".jpg");
        FileOutputStream fos = new FileOutputStream(file);

        byte[] bytes = new byte[1024];
        int readCount;
        while ((readCount = in.read()) != -1) {
            fos.write(bytes, 0, readCount);
        }
        OutputStream out = socket.getOutputStream();
        out.write("上传成功！".getBytes());
        fos.close();
        out.close();
        serverSocket.close();
    }
}
